package com.cn.qtms.common.page;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@NoArgsConstructor
/**
 * @author zhangyang
 */
public class PageReq implements Serializable {

    public static final String PO_PAGE = "page";
    public static final String PO_SIZE = "size";
    public static final String PO_SORT = "sort";
    public static final String PO_SORD = "sord";
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 1L;
    /**
     * 排序字段
     */
    private String sort;
    /**
     * 排序顺序 true是正序 false是倒序
     */
    private Boolean sord;
    /**
     * 页面
     */
    private Integer page;
    /**
     * 单页条数
     */
    private Integer size;

    public Sort getPageSort() {
        Direction pageDirection = getPageDirection();
        List<String> sorts = new ArrayList<>();
        if (getSort() != null &&  !StringUtils.isEmpty(getSort())) {
            sorts.add(getSort());
            return new Sort(pageDirection, sorts);
        }
        return null;
    }

    public Direction getPageDirection() {
        Direction direction = Direction.DESC;
        if (sord != null && sord) {
            direction = Direction.ASC;
        }
        return direction;
    }

    @SuppressWarnings("deprecation")
    private Pageable getPageable() {
        Sort pageSort = getPageSort();
        if (pageSort == null) {
            return PageRequest.of(page - 1, size);
        } else {
            return PageRequest.of(page - 1, size, pageSort);
        }
    }

    @SuppressWarnings("deprecation")
    private Pageable getPageableStartByZero() {
        Sort pageSort = getPageSort();
        if (pageSort == null) {
            return PageRequest.of(page, size);
        } else {
            return PageRequest.of(page, size, pageSort);
        }
    }

    @SuppressWarnings("deprecation")
    public static Pageable getPageable(PageReq pageReq) {
        if (pageReq == null) {
            return PageRequest.of(0, 20);
        } else {
            return pageReq.getPageable();
        }
    }

    @SuppressWarnings("deprecation")
    public static Pageable getPageable(PageReq pageReq, boolean start0) {
        if (pageReq == null) {
            return PageRequest.of(0, 20);
        } else {
            if (start0) {
                return pageReq.getPageableStartByZero();
            } else {
                return pageReq.getPageable();
            }
        }
    }

    public PageReq(Integer page, Integer size) {
        this.page = page;
        this.size = size;
    }
}
